import React, { useState, useRef, useEffect } from 'react';
import { useModel } from 'umi';
import { Avatar, List, Drawer, Space, Input, Button, message } from 'antd';
import { Css2dObject } from '@/utils/three/xThree';
import { LikeOutlined, MessageOutlined } from '@ant-design/icons';
import { findMessageByMap, insertMessage } from '@/services/swagger/messageController';
import Ws from '@/utils/ws';
const { TextArea } = Input;
import styles from './index.less';
let myWebSocket;
const LeaveMessage: React.FC = () => {
  const [open, setOpen] = useState(false);
  const textAreaRef = useRef<any>(null);
  const divObject = useRef<any>(null);
  const [leaveMessageInfo, setLeaveMessageInfo] = useState({ text: '请输入留言内容' });
  const leaveMessageRef = useRef(null);
  const currentObject = useRef<any>(null);

  const { panoramaData } = useModel('Panorama.data', (ret) => ({
    panoramaData: ret.panoramaData,
  }));

  const data = Array.from({ length: 3 }).map((_, i) => ({
    href: 'https://ant.design',
    title: `张${i}`,
    avatar: 'https://joeschmoe.io/api/v1/random',
    description: 'aaaaaa',
    content: 'bbbbbbbb',
  }));
  const IconText = ({ icon, text }: { icon: React.FC; text: string }) => (
    <Space>
      {React.createElement(icon)}
      {text}
    </Space>
  );

  const addLeaveMessageObject = () => {
    setLeaveMessageInfo({
      text: '请输入留言内容',
    });
    if (divObject.current) {
      const leaveMessage: any = leaveMessageRef.current;
      leaveMessage.style.display = 'flex !important';
      const element: any = leaveMessage?.cloneNode(true);
      currentObject.current = divObject.current.add(element, {
        name: 'selectedMessage',
        draggable: true,
      });
    }
  };
  const removeLeaveMessage = () => {
    if (divObject.current) {
      divObject.current.remove('name', 'selectedMessage');
    }
  };
  const showDrawer = () => {
    if (open) {
      removeLeaveMessage();
    } else {
      addLeaveMessageObject();
    }
    setOpen(!open);

    if (textAreaRef.current) {
      textAreaRef.current.focus();
    }
  };

  const addMessage = async () => {
    const position = JSON.stringify(currentObject.current?.position) || '';
    const { code } = await insertMessage({
      ems_message_info: leaveMessageInfo.text,
      ems_message_panoramaid: panoramaData?.ems_panorama_id,
      ems_message_location: position,
    });
    if (code === 200) {
      message.success('发布成功！');
      setLeaveMessageInfo({ text: '' });
      removeLeaveMessage();
      setOpen(false);
    }
  };

  const addMessageObject = ({
    info = '',
    position = null,
    draggable = false,
    name = 'leaveMessage',
  }) => {
    const leaveMessageInfo = info?.length > 12 ? info?.substring(0, 13) + '...' : info;
    const leaveMessage: any = leaveMessageRef.current?.cloneNode(true);
    const dataBox = leaveMessage.querySelector('.leaveMessageInfo');
    dataBox.textContent = leaveMessageInfo;
    leaveMessage.style.display = 'flex !important';
    divObject.current.add(leaveMessage, {
      position,
      name,
      draggable: draggable,
    });
  };

  const queryMessage = async () => {
    const { result } = await findMessageByMap({
      pageNum: 1,
      pageSize: 10,
      ems_message_panoramaid: panoramaData?.ems_panorama_id,
    });
    if (divObject.current) {
      divObject.current.removeAll();
    }

    divObject.current = new Css2dObject(window.viewer);
    result?.list?.forEach((item) => {
      addMessageObject({
        info: item.ems_message_info,
        position: JSON.parse(item.ems_message_location || '{x:25,y:0.35,z:-12.82}'),
        draggable: false,
      });
    });
  };

  const initWs = () => {
    const wsParams = {
      url: `ws://${location.host}/wsUrl/message/realtimeDisplay?panoramaid=${panoramaData.ems_panorama_id}`,
      callback: (data: string) => {
        if (data) {
          const jsonData = JSON.parse(data);
          addMessageObject({
            info: jsonData.ems_message_info,
            position: JSON.parse(jsonData.ems_message_location || '{x:25,y:0.35,z:-12.82}'),
            draggable: false,
            name: 'leaveMessage',
          });
        }
      },
    };
    myWebSocket = new Ws(wsParams);
    myWebSocket.connect();
  };

  useEffect(() => {
    if (window.panorama && panoramaData?.ems_panorama_id) {
      queryMessage();
      initWs();
    }
  }, [window.panorama, panoramaData]);

  return (
    <>
      <div ref={leaveMessageRef} className={styles.leaveMessageBox} style={{ display: 'none' }}>
        <img
          src={require('@/assets/images/panorama/icon/user.jpg')}
          alt=""
          className={styles.leaveMessageImg}
        />
        <span className="leaveMessageInfo">
          {leaveMessageInfo?.text?.length > 12
            ? leaveMessageInfo?.text?.substring(0, 13) + '...'
            : leaveMessageInfo?.text}
        </span>
      </div>
      <div
        className="leaveMessage"
        onClick={showDrawer}
        style={{
          cursor: 'pointer',
          userSelect: 'none',
          color: `${open ? '#1890ff' : '#fff'}`,
        }}
      >
        <MessageOutlined style={{ fontSize: 22 }} className="icon-leaveMessage" />
        <div>留言</div>
      </div>
      {open && (
        <div className={styles.leaveMessageOption}>
          {/* <div>留言</div> */}
          <Space direction="vertical" style={{ width: '100%', marginTop: 'auto' }}>
            <TextArea
              ref={textAreaRef} // 将引用赋给 TextArea
              placeholder="请输入留言！"
              onChange={(e) => {
                setLeaveMessageInfo({
                  text: e.target.value,
                });
                const leaveMessage = currentObject.current.element;
                const dataBox = leaveMessage.querySelector('.leaveMessageInfo');
                dataBox.textContent = e.target.value;
              }}
            />
            <Button type="primary" onClick={addMessage}>
              发布
            </Button>
          </Space>
        </div>
      )}
      {/* <Drawer
        title="留言列表"
        onClose={onClose}
        open={open}
        mask={false}
        bodyStyle={{ padding: '20px', display: 'flex', flexDirection: 'column' }}
      >
        <List
          itemLayout="vertical"
          size="small"
          dataSource={data}
          footer={<div></div>}
          renderItem={(item) => (
            <List.Item
              key={item.title}
              actions={[
                <IconText icon={LikeOutlined} text="156" key="list-vertical-like-o" />,
                <IconText icon={MessageOutlined} text="2" key="list-vertical-message" />,
              ]}
            >
              <List.Item.Meta
                avatar={<Avatar src={item.avatar} />}
                title={<a href={item.href}>{item.title}</a>}
                description={item.description}
              />
              {item.content}
            </List.Item>
          )}
        />
        <Space direction="vertical" style={{ width: '100%', marginTop: 'auto' }}>
          <TextArea
            rows={4}
            onChange={(e) => {
              setLeaveMessageInfo({
                name: '张三',
                text: e.target.value,
              });
            }}
          />
          <Button type="primary">发表</Button>
        </Space>
      </Drawer> */}
    </>
  );
};

export default LeaveMessage;
